package city.spring.modules.medicalstation.doctorsOrder.controller;

import city.spring.modules.medicalstation.doctorsOrder.entity.DoctorsOrderEntity;
import city.spring.modules.medicalstation.doctorsOrder.repository.DoctorsOrderRepository;
import city.spring.modules.medicalstation.doctorsOrder.service.DoctorsOrderService;
import city.spring.modules.medicalstation.doctorsOrderRecord.entity.DoctorsOrderRecordEntity;
import city.spring.modules.medicalstation.doctorsOrderRecord.service.DoctorsOrderRecordService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Controller：医嘱
 *
 * @author 谢金婷
 * @date 2020-11-09 09:46:37
 */
@RestController
@RequestMapping("/doctors_order/{doctorsOrderRecordId}")
public class DoctorsOrderController extends ApiController {
    private final DoctorsOrderService doctorsOrderService;
    private final DoctorsOrderRepository doctorsOrderRepository;
    private final DoctorsOrderRecordService doctorsOrderRecordService;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<DoctorsOrderEntity, ?>> entityOrderFields;

    public DoctorsOrderController(DoctorsOrderService doctorsOrderService, DoctorsOrderRepository doctorsOrderRepository, DoctorsOrderRecordService doctorsOrderRecordService) {
        this.doctorsOrderService = doctorsOrderService;
        this.doctorsOrderRepository = doctorsOrderRepository;
        this.doctorsOrderRecordService = doctorsOrderRecordService;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(DoctorsOrderEntity::getId);
        entityOrderFields.add(DoctorsOrderEntity::getOldmanId);
        entityOrderFields.add(DoctorsOrderEntity::getDoctorsOrder);
        entityOrderFields.add(DoctorsOrderEntity::getOrderType);
        entityOrderFields.add(DoctorsOrderEntity::getOrderDate);
        entityOrderFields.add(DoctorsOrderEntity::getEntrust);
        entityOrderFields.add(DoctorsOrderEntity::getDoctorsOrderItemId);
        entityOrderFields.add(DoctorsOrderEntity::getSpecification);
        entityOrderFields.add(DoctorsOrderEntity::getDosageUnit);
        entityOrderFields.add(DoctorsOrderEntity::getUnitprice);
        entityOrderFields.add(DoctorsOrderEntity::getApproach);
        entityOrderFields.add(DoctorsOrderEntity::getQuantity);
        entityOrderFields.add(DoctorsOrderEntity::getTaskType);
        entityOrderFields.add(DoctorsOrderEntity::getFrequency);
        entityOrderFields.add(DoctorsOrderEntity::getExecutionDate);
        entityOrderFields.add(DoctorsOrderEntity::getMark);
        entityOrderFields.add(DoctorsOrderEntity::getTotal);
        entityOrderFields.add(DoctorsOrderEntity::getOrderEndtime);
        entityOrderFields.add(DoctorsOrderEntity::getGmtCreate);
        entityOrderFields.add(DoctorsOrderEntity::getGmtModified);
    }

    @ModelAttribute
    public void getDoctorsOrderRecordId(@PathVariable String doctorsOrderRecordId) {
        if (doctorsOrderRecordId == null) {
            throw new RuntimeException("医嘱记录ID必须不为空");
        }
        System.out.println("doctorsOrderRecordId" + doctorsOrderRecordId);
    }

    /**
     * 获取全部的 <strong>医嘱</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, DoctorsOrderEntity entity) {
        LambdaQueryChainWrapper<DoctorsOrderEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    @GetMapping
    public Object list(@PathVariable String doctorsOrderRecordId) {
        return success(doctorsOrderRepository.getDoctorsOrders(doctorsOrderRecordId));
    }

    @GetMapping("/{extId}")
    public Object getInfo(@PathVariable String doctorsOrderRecordId, @PathVariable String extId) {
        return success(doctorsOrderRepository.getDoctorsOrder(doctorsOrderRecordId, extId));
    }

    @PostMapping
    public Object addAll(@PathVariable String doctorsOrderRecordId, @RequestBody List<DoctorsOrderEntity> doctorsOrders) {

        // 查出已有的数据
        List<DoctorsOrderEntity> dbDoctorsOrders = doctorsOrderRepository.getDoctorsOrders(doctorsOrderRecordId);
        // 数据库已经存在的班次列表
        Set<String> dbDoctorsOrderIdsSet = dbDoctorsOrders.stream()
                .map(DoctorsOrderEntity::getId)
                .collect(Collectors.toSet());
        DoctorsOrderRecordEntity doctorsOrderRecordEntity = doctorsOrderRecordService.getById(doctorsOrderRecordId);
        // 过滤掉已经存在数据库的数据
        List<DoctorsOrderEntity> needSaveDoctorsOrders = doctorsOrders.stream()
                .filter(item -> {
                    item.setDoctorsOrderRecordId(doctorsOrderRecordId);
                    item.setOldmanId(doctorsOrderRecordEntity.getOldmanId());
                    item.setStartDoctor(doctorsOrderRecordEntity.getStartDoctor());
                    String Id = item.getId();
                    // 过滤出不存在数据库中的数据
                    return !dbDoctorsOrderIdsSet.contains(Id);
                }).collect(Collectors.toList());
        if (!needSaveDoctorsOrders.isEmpty()) {
            doctorsOrderService.saveOrUpdateBatch(needSaveDoctorsOrders);
        }

        return success(null);
    }

    @PutMapping("/{extId}")
    public Object update(@PathVariable String doctorsOrderRecordId, @PathVariable String extId, @RequestBody DoctorsOrderEntity extEntity) {
        extEntity.setId(extId);
        extEntity.setDoctorsOrderRecordId(doctorsOrderRecordId);
        doctorsOrderService.updateDoctorsOrder(extEntity);
        return success(null);
    }

    /**
     * 删除一个 <strong>医嘱</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("/{id}")
    public Object delete(@PathVariable String id) {
        doctorsOrderService.deleteDoctorsOrder(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>医嘱</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        doctorsOrderService.deleteDoctorsOrder(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<DoctorsOrderEntity> buildLambdaQuery(DoctorsOrderEntity entity) {
        LambdaQueryChainWrapper<DoctorsOrderEntity> lambdaQuery = doctorsOrderService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), DoctorsOrderEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getOldmanId()), DoctorsOrderEntity::getOldmanId, entity.getOldmanId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDoctorsOrder()), DoctorsOrderEntity::getDoctorsOrder, entity.getDoctorsOrder());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getOrderType()), DoctorsOrderEntity::getOrderType, entity.getOrderType());
        lambdaQuery.eq(entity.getOrderDate() != null, DoctorsOrderEntity::getOrderDate, entity.getOrderDate());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getEntrust()), DoctorsOrderEntity::getEntrust, entity.getEntrust());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDoctorsOrderItemId()), DoctorsOrderEntity::getDoctorsOrderItemId, entity.getDoctorsOrderItemId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getSpecification()), DoctorsOrderEntity::getSpecification, entity.getSpecification());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getDosageUnit()), DoctorsOrderEntity::getDosageUnit, entity.getDosageUnit());
        lambdaQuery.eq(entity.getUnitprice() != null, DoctorsOrderEntity::getUnitprice, entity.getUnitprice());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getApproach()), DoctorsOrderEntity::getApproach, entity.getApproach());
        lambdaQuery.eq(entity.getQuantity() != null, DoctorsOrderEntity::getQuantity, entity.getQuantity());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getTaskType()), DoctorsOrderEntity::getTaskType, entity.getTaskType());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getFrequency()), DoctorsOrderEntity::getFrequency, entity.getFrequency());
        lambdaQuery.eq(entity.getExecutionDate() != null, DoctorsOrderEntity::getExecutionDate, entity.getExecutionDate());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getMark()), DoctorsOrderEntity::getMark, entity.getMark());
        lambdaQuery.eq(entity.getTotal() != null, DoctorsOrderEntity::getTotal, entity.getTotal());
        lambdaQuery.eq(entity.getOrderEndtime() != null, DoctorsOrderEntity::getOrderEndtime, entity.getOrderEndtime());
        lambdaQuery.eq(entity.getGmtCreate() != null, DoctorsOrderEntity::getGmtCreate, entity.getGmtCreate());
        lambdaQuery.eq(entity.getGmtModified() != null, DoctorsOrderEntity::getGmtModified, entity.getGmtModified());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<DoctorsOrderEntity> buildQuery(DoctorsOrderEntity entity) {
        QueryWrapper<DoctorsOrderEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getOldmanId()), "oldman_id", entity.getOldmanId());
        wrapper.like(StringUtils.isNotBlank(entity.getDoctorsOrder()), "doctors_order", entity.getDoctorsOrder());
        wrapper.like(StringUtils.isNotBlank(entity.getOrderType()), "order_type", entity.getOrderType());
        wrapper.eq(entity.getOrderDate() != null, "order_date", entity.getOrderDate());
        wrapper.like(StringUtils.isNotBlank(entity.getEntrust()), "entrust", entity.getEntrust());
        wrapper.like(StringUtils.isNotBlank(entity.getDoctorsOrderItemId()), "doctors_order_item_id", entity.getDoctorsOrderItemId());
        wrapper.like(StringUtils.isNotBlank(entity.getSpecification()), "specification", entity.getSpecification());
        wrapper.like(StringUtils.isNotBlank(entity.getDosageUnit()), "dosage_unit", entity.getDosageUnit());
        wrapper.eq(entity.getUnitprice() != null, "unitprice", entity.getUnitprice());
        wrapper.like(StringUtils.isNotBlank(entity.getApproach()), "approach", entity.getApproach());
        wrapper.eq(entity.getQuantity() != null, "quantity", entity.getQuantity());
        wrapper.like(StringUtils.isNotBlank(entity.getTaskType()), "task_type", entity.getTaskType());
        wrapper.like(StringUtils.isNotBlank(entity.getFrequency()), "frequency", entity.getFrequency());
        wrapper.eq(entity.getExecutionDate() != null, "execution_date", entity.getExecutionDate());
        wrapper.like(StringUtils.isNotBlank(entity.getMark()), "mark", entity.getMark());
        wrapper.eq(entity.getTotal() != null, "total", entity.getTotal());
        wrapper.eq(entity.getOrderEndtime() != null, "order_endtime", entity.getOrderEndtime());
        wrapper.eq(entity.getGmtCreate() != null, "gmt_create", entity.getGmtCreate());
        wrapper.eq(entity.getGmtModified() != null, "gmt_modified", entity.getGmtModified());
        return wrapper;
    }

}
